package com.jic.order.impl;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.order.entity.OrderManualDelivery;
import com.jic.order.manage.request.OrderManualDeliveryRequest;
import com.jic.order.manage.response.OrderManualDeliveryResponse;
import com.jic.order.mapper.OrderManualDeliveryMapper;
import com.jic.order.service.OrderManualDeliveryService;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.response.ProductAfterInfoByIdResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 订单手动转交货表
 *
 * @author :
 * @email :
 * @since : 2020-05-28 01:53:34
 */
@Slf4j
@Service
public class OrderManualDeliveryServiceImpl implements OrderManualDeliveryService {

  @Autowired
  RedisClientTemplate redisClientTemplate;

  @Autowired
  private OrderManualDeliveryMapper orderManualDeliveryMapper;

  @Resource
  private ProductListApi productListApi;

  @Override
  public RestResult insert(OrderManualDeliveryRequest request) {
    try {
      if (StringUtils.isEmpty(request.getOrderNo())) {
        return RestResult.error("9999", "请求参数不能为空!");
      }

      String userStr = redisClientTemplate.get(request.getToken());
      Map sysUser = JSONArray.parseObject(userStr, Map.class);

      OrderManualDelivery orderManualDelivery = new OrderManualDelivery();
      BeanUtils.copyProperties(request, orderManualDelivery);
      orderManualDelivery.setTransferOutMerchantId(Long.valueOf(sysUser.get("merchantId").toString()));
      orderManualDelivery.setTransferOutMerchantName(sysUser.get("username").toString());
      orderManualDelivery.setOrderStatus(1);
      for (int i = 0; i < request.getProductIdList().size(); i++) {
        long productCount = orderManualDeliveryMapper.queryByOrderNoAndProductId(request.getOrderNo(), request.getProductIdList().get(i));
        if (productCount >= 1) {
          continue;
        }
        orderManualDelivery.setProductId(request.getProductIdList().get(i));
        orderManualDelivery.setProductNum(request.getProductNumList().get(i));
        orderManualDelivery.setProductPrice(request.getProductPriceList().get(i));
        orderManualDeliveryMapper.insert(orderManualDelivery);
      }
    } catch (Exception e) {
      log.error("orderManualDeliveryMapper.insert ========>", e);
    }
    return RestResult.success("新增手动转交货单执行成功");
  }

  @Override
  public long delete(Long id) {
    return orderManualDeliveryMapper.delete(id);
  }

  @Override
  public RestResult update(OrderManualDelivery orderManualDelivery) {
    try {
      if (StringUtils.isEmpty(orderManualDelivery.getOrderNo())) {
        log.error("修改手动转交货单执行失败==><>>>>>{}", orderManualDelivery.getOrderNo());
      }
      List<Long> longList = orderManualDeliveryMapper.queryById(orderManualDelivery.getOrderNo());
      for (int i = 0; i < longList.size(); i++) {
        orderManualDelivery.setId(longList.get(i));
        orderManualDeliveryMapper.update(orderManualDelivery);
      }
    } catch (Exception e) {
      log.error("orderManualDeliveryMapper.insert ========>", e);
    }
    return RestResult.success("修改手动转交货单执行成功");
  }

  @Override
  public RestResult<List<OrderManualDeliveryResponse>> query(OrderManualDelivery orderManualDelivery) {
    List<OrderManualDeliveryResponse> query = orderManualDeliveryMapper.query(orderManualDelivery)
        .stream().map(item -> {
          OrderManualDeliveryResponse response = new OrderManualDeliveryResponse();
          BeanUtils.copyProperties(item, response);

          if (null != item.getProductId()) {
            // 调用商品信息
            ProductAfterInfoByIdResponse product = productListApi.queryProductInfoById(item.getProductId()).getData();
            if (null != product) {
              response.setChineseName(product.getChineseName());
              response.setPictureUrl(product.getPictureUrl());
            }
          }

          return response;
        }).collect(Collectors.toList());

    return RestResult.success(query);
  }

  @Override
  public RestResult<PageResult<OrderManualDeliveryResponse>> queryPage(OrderManualDelivery orderManualDelivery, Page pageQuery) {
    // 计算下标
    int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();

    List<OrderManualDeliveryResponse> list = orderManualDeliveryMapper.queryPage(startIndex, pageQuery.getLimit(), orderManualDelivery)
        .stream().map(item -> {
          OrderManualDeliveryResponse response = new OrderManualDeliveryResponse();
          BeanUtils.copyProperties(item, response);
          return response;
        }).collect(Collectors.toList());

    long count = orderManualDeliveryMapper.queryPageCount(orderManualDelivery);

    PageResult<OrderManualDeliveryResponse> pageResult = new PageResult<>();
    pageResult.setRows(list);
    pageResult.setTotal(count);
    return RestResult.success(pageResult);
  }
}